// 游戏引擎服务

import { 
  useGameStore, 
  useResourcesStore, 
  useBuildingsStore, 
  useTechnologyStore, 
  useShipsStore, 
  useDiplomacyStore 
} from '@/stores'
import type { GameEvent } from '@/types'

export interface GameEngineConfig {
  tickInterval: number // 游戏循环间隔（毫秒）
  autoSaveInterval: number // 自动保存间隔（毫秒）
  maxTicksPerSecond: number // 最大每秒tick数
}

export class GameEngine {
  private static instance: GameEngine
  private isRunning = false
  private tickTimer: number | null = null
  private autoSaveTimer: number | null = null
  private lastTickTime = 0
  private tickCount = 0
  private config: GameEngineConfig

  // Store引用
  private gameStore = useGameStore()
  private resourcesStore = useResourcesStore()
  private buildingsStore = useBuildingsStore()
  private technologyStore = useTechnologyStore()
  private shipsStore = useShipsStore()
  private diplomacyStore = useDiplomacyStore()

  constructor(config: Partial<GameEngineConfig> = {}) {
    this.config = {
      tickInterval: 1000, // 1秒
      autoSaveInterval: 300000, // 5分钟
      maxTicksPerSecond: 10,
      ...config
    }
  }

  static getInstance(config?: Partial<GameEngineConfig>): GameEngine {
    if (!GameEngine.instance) {
      GameEngine.instance = new GameEngine(config)
    }
    return GameEngine.instance
  }

  // 初始化游戏引擎
  static async initialize(config?: Partial<GameEngineConfig>): Promise<void> {
    try {
      console.log('🎮 初始化游戏引擎...')
      
      // 获取实例以确保单例模式正常工作
      const instance = GameEngine.getInstance(config)
      
      // 游戏引擎初始化完成，但不自动启动
      // 需要手动调用 startGameLoop() 来启动游戏循环
      
      console.log('✅ 游戏引擎初始化完成')
    } catch (error) {
      console.error('❌ 游戏引擎初始化失败:', error)
      throw new Error(`游戏引擎初始化失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  // 启动游戏循环
  static async startGameLoop(): Promise<void> {
    try {
      console.log('🔄 启动游戏循环...')
      
      const instance = GameEngine.getInstance()
      instance.start()
      
      console.log('✅ 游戏循环已启动')
    } catch (error) {
      console.error('❌ 启动游戏循环失败:', error)
      throw new Error(`启动游戏循环失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  // 启动游戏引擎
  start(): void {
    if (this.isRunning) return

    this.isRunning = true
    this.lastTickTime = Date.now()
    
    // 启动游戏循环
    this.tickTimer = window.setInterval(() => {
      this.tick()
    }, this.config.tickInterval)

    // 启动自动保存
    this.autoSaveTimer = window.setInterval(() => {
      this.autoSave()
    }, this.config.autoSaveInterval)

    console.log('游戏引擎已启动')
  }

  // 停止游戏引擎
  stop(): void {
    if (!this.isRunning) return

    this.isRunning = false
    
    if (this.tickTimer) {
      clearInterval(this.tickTimer)
      this.tickTimer = null
    }

    if (this.autoSaveTimer) {
      clearInterval(this.autoSaveTimer)
      this.autoSaveTimer = null
    }

    console.log('游戏引擎已停止')
  }

  // 暂停游戏
  pause(): void {
    this.gameStore.pauseGame()
    if (this.tickTimer) {
      clearInterval(this.tickTimer)
      this.tickTimer = null
    }
  }

  // 恢复游戏
  resume(): void {
    this.gameStore.resumeGame()
    if (this.isRunning && !this.tickTimer) {
      this.tickTimer = window.setInterval(() => {
        this.tick()
      }, this.config.tickInterval)
    }
  }

  // 设置游戏速度
  setSpeed(speed: number): void {
    this.gameStore.setGameSpeed(speed)
    
    // 重新设置tick间隔
    if (this.tickTimer) {
      clearInterval(this.tickTimer)
      const newInterval = this.config.tickInterval / speed
      this.tickTimer = window.setInterval(() => {
        this.tick()
      }, newInterval)
    }
  }

  // 游戏主循环
  private tick(): void {
    if (!this.gameStore.isRunning || this.gameStore.isPaused) return

    const currentTime = Date.now()
    const deltaTime = currentTime - this.lastTickTime
    const gameSpeed = this.gameStore.gameSpeed

    // 限制tick频率
    if (deltaTime < (1000 / this.config.maxTicksPerSecond)) return

    this.lastTickTime = currentTime
    this.tickCount++

    // 更新游戏时间
    this.gameStore.updateGameTime(deltaTime * gameSpeed)

    // 更新各个系统
    this.updateResources(deltaTime * gameSpeed)
    this.updateBuildings(deltaTime * gameSpeed)
    this.updateTechnology(deltaTime * gameSpeed)
    this.updateShips(deltaTime * gameSpeed)
    this.updateDiplomacy(deltaTime * gameSpeed)

    // 处理游戏事件
    this.processGameEvents()

    // 检查成就
    this.checkAchievements()

    // 更新统计数据
    this.updateStatistics(deltaTime)
  }

  // 更新资源系统
  private updateResources(deltaTime: number): void {
    this.resourcesStore.updateProduction(deltaTime)
  }

  // 更新建筑系统
  private updateBuildings(deltaTime: number): void {
    this.buildingsStore.updateProduction(deltaTime)
    this.buildingsStore.updateBuildQueue(deltaTime)
  }

  // 更新科技系统
  private updateTechnology(deltaTime: number): void {
    this.technologyStore.updateResearch(deltaTime)
  }

  // 更新舰船系统
  private updateShips(deltaTime: number): void {
    this.shipsStore.updateBuildQueue(deltaTime)
  }

  // 更新外交系统
  private updateDiplomacy(deltaTime: number): void {
    this.diplomacyStore.updateMissions(deltaTime)
  }

  // 处理游戏事件
  private processGameEvents(): void {
    const events = this.gameStore.pendingEvents
    
    events.forEach(event => {
      this.processEvent(event)
    })

    // 清空已处理的事件
    this.gameStore.clearProcessedEvents()

    // 生成随机事件
    this.generateRandomEvents()
  }

  // 处理单个事件
  private processEvent(event: GameEvent): void {
    console.log(`处理事件: ${event.title}`)

    // 应用事件效果
    event.effects?.forEach(effect => {
      this.applyEffect(effect)
    })

    // 标记事件为已处理
    this.gameStore.markEventAsProcessed(event.id)
  }

  // 应用效果
  private applyEffect(effect: any): void {
    switch (effect.type) {
      case 'resource':
        this.resourcesStore.addResource(effect.resourceId, effect.amount)
        break
      case 'building':
        // 应用建筑效果
        break
      case 'technology':
        // 应用科技效果
        break
      case 'ship':
        // 应用舰船效果
        break
      case 'diplomacy':
        // 应用外交效果
        break
    }
  }

  // 生成随机事件
  private generateRandomEvents(): void {
    // 基于游戏状态和时间生成随机事件
    const gameTime = this.gameStore.gameTime
    const lastEventTime = this.gameStore.lastEventTime

    // 每10分钟游戏时间检查一次随机事件
    if (gameTime - lastEventTime > 600000) {
      const eventChance = Math.random()
      
      if (eventChance < 0.1) { // 10%概率
        this.generateRandomEvent()
      }
      
      this.gameStore.updateLastEventTime(gameTime)
    }
  }

  // 生成随机事件
  private generateRandomEvent(): void {
    const eventTypes = [
      'resource_discovery',
      'pirate_attack',
      'trade_opportunity',
      'diplomatic_incident',
      'technological_breakthrough'
    ]

    const eventType = eventTypes[Math.floor(Math.random() * eventTypes.length)]
    const event = this.createEventByType(eventType)
    
    if (event) {
      this.gameStore.addEvent(event)
    }
  }

  // 根据类型创建事件
  private createEventByType(type: string): GameEvent | null {
    const eventId = `event_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    switch (type) {
      case 'resource_discovery':
        return {
          id: eventId,
          type: 'random',
          title: '资源发现',
          description: '探索队发现了一个富含稀有矿物的小行星带。',
          effects: [
            {
              type: 'resource',
              resourceId: 'rare_metals',
              amount: 1000,
              description: '获得1000稀有金属'
            }
          ],
          choices: [],
          isActive: true,
          createdAt: Date.now()
        }
      
      case 'pirate_attack':
        return {
          id: eventId,
          type: 'crisis',
          title: '海盗袭击',
          description: '海盗舰队正在接近我们的贸易航线。',
          effects: [],
          choices: [
            {
              id: 'fight',
              text: '迎战',
              effects: [
                {
                  type: 'resource',
                  resourceId: 'energy',
                  amount: -500,
                  description: '消耗500能量'
                }
              ]
            },
            {
              id: 'negotiate',
              text: '谈判',
              effects: [
                {
                  type: 'resource',
                  resourceId: 'credits',
                  amount: -1000,
                  description: '支付1000信用点'
                }
              ]
            }
          ],
          isActive: true,
          createdAt: Date.now()
        }
      
      default:
        return null
    }
  }

  // 检查成就
  private checkAchievements(): void {
    // 检查各种成就条件
    this.checkResourceAchievements()
    this.checkBuildingAchievements()
    this.checkTechnologyAchievements()
    this.checkShipAchievements()
    this.checkDiplomacyAchievements()
  }

  // 检查资源相关成就
  private checkResourceAchievements(): void {
    const resources = this.resourcesStore.resources
    
    // 检查资源数量成就
    Object.entries(resources).forEach(([resourceId, amount]) => {
      if (amount >= 10000) {
        this.gameStore.unlockAchievement(`resource_${resourceId}_10k`)
      }
      if (amount >= 100000) {
        this.gameStore.unlockAchievement(`resource_${resourceId}_100k`)
      }
    })
  }

  // 检查建筑相关成就
  private checkBuildingAchievements(): void {
    const buildings = this.buildingsStore.buildings
    const buildingCount = buildings.length
    
    if (buildingCount >= 10) {
      this.gameStore.unlockAchievement('builder_novice')
    }
    if (buildingCount >= 50) {
      this.gameStore.unlockAchievement('builder_expert')
    }
    if (buildingCount >= 100) {
      this.gameStore.unlockAchievement('builder_master')
    }
  }

  // 检查科技相关成就
  private checkTechnologyAchievements(): void {
    const researchedTechs = this.technologyStore.researchedTechnologies
    const techCount = researchedTechs.length
    
    if (techCount >= 5) {
      this.gameStore.unlockAchievement('researcher_novice')
    }
    if (techCount >= 20) {
      this.gameStore.unlockAchievement('researcher_expert')
    }
    if (techCount >= 50) {
      this.gameStore.unlockAchievement('researcher_master')
    }
  }

  // 检查舰船相关成就
  private checkShipAchievements(): void {
    const ships = this.shipsStore.ships
    const shipCount = ships.length
    
    if (shipCount >= 5) {
      this.gameStore.unlockAchievement('admiral_novice')
    }
    if (shipCount >= 25) {
      this.gameStore.unlockAchievement('admiral_expert')
    }
    if (shipCount >= 100) {
      this.gameStore.unlockAchievement('admiral_master')
    }
  }

  // 检查外交相关成就
  private checkDiplomacyAchievements(): void {
    const alliedFactions = this.diplomacyStore.alliedFactions
    const treaties = this.diplomacyStore.activeTreaties
    
    if (alliedFactions.length >= 1) {
      this.gameStore.unlockAchievement('diplomat_first_ally')
    }
    if (treaties.length >= 5) {
      this.gameStore.unlockAchievement('diplomat_treaty_maker')
    }
  }

  // 更新统计数据
  private updateStatistics(deltaTime: number): void {
    this.gameStore.updatePlayTime(deltaTime)
    
    // 每分钟更新一次详细统计
    if (this.tickCount % 60 === 0) {
      this.gameStore.updateStatistics({
        totalResources: Object.values(this.resourcesStore.resources).reduce((sum, amount) => sum + amount, 0),
        totalBuildings: this.buildingsStore.buildings.length,
        totalTechnologies: this.technologyStore.researchedTechnologies.length,
        totalShips: this.shipsStore.ships.length,
        totalFleets: this.shipsStore.fleets.length
      })
    }
  }

  // 自动保存
  private autoSave(): void {
    if (this.gameStore.isRunning && !this.gameStore.isPaused) {
      this.gameStore.saveGame('autosave', '自动保存')
      console.log('自动保存完成')
    }
  }

  // 获取引擎状态
  getStatus() {
    return {
      isRunning: this.isRunning,
      isPaused: this.gameStore.isPaused,
      gameSpeed: this.gameStore.gameSpeed,
      tickCount: this.tickCount,
      gameTime: this.gameStore.gameTime,
      playTime: this.gameStore.playTime
    }
  }

  // 重置引擎
  reset(): void {
    this.stop()
    this.tickCount = 0
    this.lastTickTime = 0
  }
}